package com.sau.pixelcart.controller;


import com.sau.pixelcart.common.result.PageResult;
import com.sau.pixelcart.common.result.Result;
import com.sau.pixelcart.common.utils.AliOssUtil;
import com.sau.pixelcart.domain.dto.ProductDTO;
import com.sau.pixelcart.domain.dto.ProductPageDTO;
import com.sau.pixelcart.domain.vo.ProductVO;
import com.sau.pixelcart.service.IProductInventoryService;
import com.sau.pixelcart.service.IProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.UUID;

/**
 * <p>
 * 商品核心信息表 前端控制器
 * </p>
 *
 * @author Inton
 * @since 2025-03-08
 */
@RestController
@RequestMapping("/product")
@Slf4j
public class ProductController {

    @Autowired
    private AliOssUtil aliOssUtil;

    @Autowired
    private IProductService productService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 商品分页查询
     * @return
     */
    @GetMapping("/list")
    public Result list(ProductPageDTO productPageDTO){
        log.info("商品分页查询...{}",productPageDTO);

        //查看Redis中是否有对应数据
        String key = "product_" + productPageDTO.getPage() + "_" + productPageDTO.getPageSize() + "_" + productPageDTO.getCategoryId() + "_" + productPageDTO.getKeyword();
        List<ProductVO> list = (List<ProductVO>) redisTemplate.opsForValue().get(key);
        if (list != null && list.size() > 0){
            //说明redis中有值，直接使用值返回
            log.info("使用redis中的product列表...");
            PageResult<ProductVO> pageResult = new PageResult<>();
            pageResult.setTotal(productPageDTO.getPageSize());
            pageResult.setRecords(list);
            return Result.success(pageResult);
        }

        //没有进行数据库查询操作，并将其加载到Redis中
        PageResult<ProductVO> pageResult = productService.pageQuery(productPageDTO);

        //将查到的数据添加到redis
        log.info("开始转储到redis...{}",pageResult);
        redisTemplate.opsForValue().set(key,pageResult.getRecords());
        return Result.success(pageResult);
    }

    /**
     * 添加/修改商品
     * @param productDTO
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody ProductDTO productDTO){
        log.info("开始添加/更新商品:{}",productDTO);

        //清空redis中product相关的数据
        String key = "product_*";
        Set keys = redisTemplate.keys(key);
        if (keys != null && keys.size() > 0){
            redisTemplate.delete(keys);
        }

        //进入Service逻辑中，处理添加/修改
        String id = productService.save(productDTO);

        return Result.success(id);
    }

    /**
     * 获取商品详情
     * @param productId
     * @return
     */
    @GetMapping("/{productId}")
    public Result getProductById(@PathVariable String productId){
        log.info("获取商品详情：{}",productId);
        ProductVO productVO = productService.getProductById(productId);
        return Result.success(productVO);
    }

    /**
     * 改变商品状态
     * @param productDTO
     * @return
     */
    @PostMapping("/status")
    public Result changeStatus(@RequestBody ProductDTO productDTO){
        log.info("修改商品状态，{}",productDTO.getId());
        productService.changeStatus(productDTO);

        //清空redis中product相关的数据
        String key = "product_*";
        Set keys = redisTemplate.keys(key);
        if (keys != null && keys.size() > 0){
            redisTemplate.delete(keys);
        }

        return Result.success();
    }

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/image/upload")
    public Result upload(MultipartFile file) {
        log.info("文件上传{}",file);
        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));

            String objectName = UUID.randomUUID() + extension;
            //文件请求路径为path
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            return Result.success(filePath);
        } catch (IOException e) {
            log.error("文件上传失败 {}",e);
        }
        return Result.error("上传失败");
    }

    /**
     * 删除商品
     * @param productId
     * @return
     */
    @DeleteMapping("/{productId}")
    public Result delete(@PathVariable String productId){
        log.info("删除商品");
        productService.deleteById(productId);

        //清空redis中product相关的数据
        String key = "product_*";
        Set productSet = redisTemplate.keys(key);
        if (productSet != null && productSet.size() > 0){
            redisTemplate.delete(productSet);
        }

        return Result.success();
    }

}
